package com.ffcs.trino.controller;

import cn.hutool.json.JSONObject;
import com.ffcs.trino.base.R;
import com.ffcs.trino.config.TrinoJdbc;
import com.ffcs.trino.domin.ResponseData;
import com.ffcs.trino.domin.SqlDataVO;
import com.ffcs.trino.service.TrinoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author zhangzhengxing
 */
@RestController
@RequiredArgsConstructor
@Api(tags = "Trino配置")
public class TrinoController {

  private final TrinoService trinoService;

  private final TrinoJdbc trinoJdbc;

  @PostMapping("/sql")
  @ApiOperation("SQL查询")
  public R<List<Map<String, Object>>> query(@RequestBody SqlDataVO sqlDataVO) {
    return R.ok(trinoJdbc.getTrinoData(sqlDataVO.getSql()));
  }

  @GetMapping("/getConfig")
  @ApiOperation("获取配置")
  public R<List<JSONObject>> getConfig() {
    return R.ok(trinoService.getConfig());
  }

  @PostMapping("/setConfig")
  @ApiOperation("写入配置")
  public R<Map<String, ResponseData>> setConfig(@RequestBody List<JSONObject> config) {
    return R.ok(trinoService.setConfig(config));
  }

  @GetMapping("/verify")
  @ApiOperation("验证数据库连接")
  @ApiParam(name = "dataBase", value = "数据库名称")
  public R<String> verify(@RequestParam("dataBase") String dataBase) {
    if (trinoJdbc.getTestConnection(dataBase).getCode() == 200) {
      return R.ok("连接成功");
    } else {
      return R.error("连接失败");
    }
  }
}
